﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using FMPCore;

namespace Client.UserControls
{
    /// <summary>
    /// Interaction logic for ucFileTransfer.xaml
    /// </summary>
    public partial class ucFileTransfer : UserControl
    {
        public ucFileTransfer()
        {
            InitializeComponent();
        }

        Queue<FileTransferMessageArgs> m_queueOfFilesToReceive = new Queue<FileTransferMessageArgs>();

        public void AddFileToReceive(FileTransferMessageArgs ftma)
        {
            m_queueOfFilesToReceive.Enqueue(ftma);
        }

        public void AddFileToSend(string filename, List<IPAddress> IPAddresses)
        {
            SendFile(filename, IPAddresses);
        }

        Int32 m_port = 13000;
        private int m_sendSize = 172032;

        private void UserControl_Initialized(object sender, EventArgs e)
        {
            SetupListener();
            //ShutdownListener();
        }

        #region Client

        private List<BackgroundWorker> m_listSendBW = new List<BackgroundWorker>();

        private void SendFile(string filename, List<IPAddress> IPAddresses)
        {
            BWSenderArgs args = new BWSenderArgs
            {
                FileName = filename,
                HostIPAddress = IPAddresses
            };

            BackgroundWorker bwSend = new BackgroundWorker();
            bwSend.WorkerSupportsCancellation = true;
            bwSend.DoWork += new DoWorkEventHandler(bwSend_DoWork);
            bwSend.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSend_RunWorkerCompleted);
            m_listSendBW.Add(bwSend);
            bwSend.RunWorkerAsync(args);
        }

        void bwSend_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            m_listReciveBW.Remove(bw);
        }

        void bwSend_DoWork(object sender, DoWorkEventArgs e)
        {
            BWSenderArgs args = e.Argument as BWSenderArgs;

            try
            {
                TcpClient client = null;

                foreach (IPAddress ip in args.HostIPAddress)
                {
                    client = new TcpClient(ip.ToString(), m_port);

                    if (client.Connected)
                    {
                        break;
                    }
                    else
                    {
                        client = null;
                    }
                }

                if (client != null)
                {
                    NetworkStream stream = client.GetStream();

                    FileStream fs = File.OpenRead(args.FileName);
                    byte[] sendData = new byte[m_sendSize];

                    int i = 0;
                    long totalBytes = 0;
                    while ((i = fs.Read(sendData, 0, sendData.Length)) != 0)
                    {
                        totalBytes += i;
                        // Send the message to the connected TcpServer.
                        stream.Write(sendData, 0, i);
                    }

                    // Close everything.
                    stream.Close();
                    client.Close();
                }
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("ArgumentNullException: {0}", ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("SocketException: {0}", ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
        }

        #endregion

        #region Listener

        TcpListener m_server;
        private BackgroundWorker m_bwListener;
        private List<BackgroundWorker> m_listReciveBW = new List<BackgroundWorker>();

        private void SetupListener()
        {
            bool serverStarted = false;

            try
            {
                IPAddress localAddr = IPAddress.Parse(IPAddress.Any.ToString());
                m_server = new TcpListener(localAddr, m_port);
                m_server.Start();
                serverStarted = true;
            }
            catch (Exception e)
            {

            }

            if (serverStarted)
            {
                m_bwListener = new BackgroundWorker();
                m_bwListener.WorkerSupportsCancellation = true;
                m_bwListener.DoWork += new DoWorkEventHandler(m_bwListener_DoWork);
                m_bwListener.RunWorkerAsync();
            }
        }

        private void ShutdownListener()
        {
            // TODO: shut down any active transfers

            m_bwListener.CancelAsync();

            if (m_server != null)
            {
                m_server.Stop();
            }
        }

        #region bwListener

        void m_bwListener_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;

            while (!e.Cancel)
            {
                if (!m_server.Pending() || m_queueOfFilesToReceive.Count == 0)
                {
                    Thread.Sleep(1000); // choose a number (in milliseconds) that makes sense
                    continue; // skip to next iteration of loop
                }
                else
                {
                    TcpClient client = m_server.AcceptTcpClient();

                    FileTransferMessageArgs ftma = m_queueOfFilesToReceive.Dequeue();

                    BWSArgs bws = new BWSArgs
                    {
                        Client = client,
                        FileName = ftma.FileName,
                        FileSize = ftma.FileLength
                    };

                    BackgroundWorker bw = new BackgroundWorker();
                    bw.WorkerSupportsCancellation = true;
                    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                    m_listReciveBW.Add(bw);
                    bw.RunWorkerAsync(bws);
                    ++i;
                }
            }
        }

        #endregion

        #region bwReciver

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            BWSArgs bws = e.Result as BWSArgs;
            bws.Client.Close();
            m_listReciveBW.Remove(bw);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BWSArgs bws = e.Argument as BWSArgs;

            NetworkStream stream = bws.Client.GetStream();
            Byte[] bytes = new Byte[m_sendSize];

            int i;

            BinaryWriter bWrite = new BinaryWriter(File.Open(bws.FileName, FileMode.OpenOrCreate));
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                bWrite.Write(bytes, 0, i);
            }
            bWrite.Close();

            e.Result = bws;
        }

        #endregion

        #endregion
    }

    public class BWSArgs
    {
        public TcpClient Client { get; set; }
        public string FileName { get; set; }
        public long FileSize { get; set; }
    }

    public class BWSenderArgs
    {
        public string FileName { get; set; }
        public List<IPAddress> HostIPAddress { get; set; }
    }
}
